package com.cs.base.quartz.core;

import com.cs.base.common.SpringBootContext;
import com.cs.base.quartz.support.BaseJob;
import com.cs.base.quartz.support.TaskInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Iterator;
import java.util.Map;

/**
 * @author wangjiahao
 * @version 1.0
 * @className asd
 * @since 2019-03-25 16:23
 */
@Slf4j
@Configuration
public class QuartzListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private QuartzManager quartzManager;

    private static int count = 0;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        if (count >= 1) {
            return;
        }
        Map<String, BaseJob> beans = SpringBootContext.getApplicationContext().getBeansOfType(BaseJob.class);
        Iterator<String> it = beans.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            BaseJob job = beans.get(key);

            TaskInfoEntity entity = new TaskInfoEntity();
            entity.setJobClassName(job.option().getJobClassName());
            entity.setCronExpression(job.option().getCron());
            entity.setJobGroup(job.option().getGroupName());
            try {
                quartzManager.addJob(entity);
            } catch (ServiceException e) {
                log.warn("任务已存在或存在异常--{}",job.option().getJobClassName());
            }
        }
        log.info("加载定时任务完成");
        count++;
    }
}
